from rest_framework import serializers
from .models import AlarmRecord
from subscriptions.serializers import (
    OPCUASubscriptionSerializer,
    MQTTSubscriptionSerializer
)
from django.utils import timezone

class AlarmRecordSerializer(serializers.ModelSerializer):
    """报警记录序列化器"""
    subscription_type_display = serializers.CharField(
        source='get_subscription_type_display',
        read_only=True
    )
    opcua_subscription = OPCUASubscriptionSerializer(read_only=True)
    mqtt_subscription = MQTTSubscriptionSerializer(read_only=True)
    data_source_name = serializers.CharField(
        source='get_data_source_name',
        read_only=True
    )
    identifier = serializers.CharField(
        source='get_identifier',
        read_only=True
    )
    acknowledged_by_username = serializers.CharField(
        source='acknowledged_by.username',
        read_only=True,
        allow_null=True
    )

    class Meta:
        model = AlarmRecord
        fields = [
            'id',
            'subscription_type',
            'subscription_type_display',
            'opcua_subscription',
            'mqtt_subscription',
            'data_source_name',
            'identifier',
            'value',
            'message',
            'created_at',
            'acknowledged',
            'acknowledged_by',
            'acknowledged_by_username',
            'acknowledged_at',
            'note'
        ]
        read_only_fields = [
            'subscription_type',
            'opcua_subscription',
            'mqtt_subscription',
            'value',
            'message',
            'created_at'
        ]

    def update(self, instance, validated_data):
        """只允许更新确认状态和备注"""
        if 'acknowledged' in validated_data:
            instance.acknowledged = validated_data['acknowledged']
            if instance.acknowledged and not instance.acknowledged_by:
                instance.acknowledged_by = self.context['request'].user
                instance.acknowledged_at = timezone.now()
            elif not instance.acknowledged:
                instance.acknowledged_by = None
                instance.acknowledged_at = None

        if 'note' in validated_data:
            instance.note = validated_data['note']

        instance.save()
        return instance

class AlarmRecordListSerializer(AlarmRecordSerializer):
    """报警记录列表序列化器（简化版）"""
    class Meta(AlarmRecordSerializer.Meta):
        fields = [
            'id',
            'subscription_type',
            'subscription_type_display',
            'data_source_name',
            'identifier',
            'value',
            'message',
            'created_at',
            'acknowledged',
            'acknowledged_by_username',
            'acknowledged_at'
        ] 